import EventManager from "../EventManager";
import SceneManager from "../framework/SceneManager";
import StageBase from "../framework/StageBase";

const { ccclass, property } = cc._decorator;

@ccclass
export default class FingerGuide extends cc.Component {

    @property(cc.Node)
    quan1: cc.Node = null;
    @property(cc.Node)
    quan2: cc.Node = null;
    @property(cc.Node)
    finger: cc.Node = null;

    private currStage: StageBase = null;
    private onNodeDestroy: Function;

    onDestroy() {
        EventManager.removeEvent(SceneManager.Event_StageOut, this.onStageOut, this);
        if (this.onNodeDestroy) {
            this.onNodeDestroy();
        }
    }

    onLoad() {
        EventManager.addEvent(SceneManager.Event_StageOut, this.onStageOut, this);
        this.currStage = SceneManager.currStage;
        this.quan1.scale = 0;
        this.quan2.scale = 0;
        this.finger.opacity = 0;
        this.finger.scale = 1.1
        cc.tween(this.finger).to(0.2, { opacity: 255, scale: 1 }).start();
    }

    start() {
        this.quanAnim(this.quan1, 0);
        this.quanAnim(this.quan2, 0.5);
    }

    private quanAnim(quan: cc.Node, delay: number) {
        this.schedule(() => {
            quan.scale = 0;
            quan.opacity = 255;
            cc.tween(quan).to(1, { scale: 1.5, opacity: 0 }).start();
        }, 1, cc.macro.REPEAT_FOREVER, delay);
    }

    /**
     * 清除当前场景内所有的手指引导
     */
    static clear() {
        try {
            let guides = cc.Canvas.instance.node.getComponentsInChildren(FingerGuide);
            guides.forEach(guide => {
                guide.node.destroy();
            });
        } catch (error) { }
    }

    onStageOut(view: StageBase) {
        if (view == this.currStage) {
            if (this.node) {
                this.node.destroy();
            }
        }
    }

    /** 淡出并删除 */
    fadeOutAndDestroy(onDestroy: Function) {
        this.onNodeDestroy = onDestroy;
        cc.tween(this.node).to(0.5, { opacity: 0 }).call(() => {
            this.node.destroy();
        }).start();
    }

}
